package object_storage

import (
	"time"

	"code.byted.org/bytertc/whiteboard_server/biz/pkg/object_storage/inner_tos"
	"code.byted.org/bytertc/whiteboard_server/biz/pkg/object_storage/s3"
	"github.com/bluele/gcache"
	"github.com/pkg/errors"
)

const (
	VendorInnerTos = "inner_tos"
	VendorVolcTos  = "volc_tos"
	VendorAliOss   = "ali_oss"
)

const (
	DefaultExpire = time.Hour
)

type Cache struct {
	gc gcache.Cache
}

var cache *Cache

func NewCache() {
	//一般一个业务方一个bucket，200已经足够大
	gc := gcache.New(200).LRU().Build()
	cache = &Cache{
		gc: gc,
	}
}

func GetCache() *Cache {
	return cache
}

// key 或可使用appID
func (c *Cache) SetClient(vendor, bucket string, client ObjectStorageClient) error {
	err := c.gc.SetWithExpire(generateKey(vendor, bucket), client, DefaultExpire)
	if err != nil {
		return errors.Wrap(err, "cache set failed")
	}
	return nil
}

func (c *Cache) GetClient(vendor, bucket string) ObjectStorageClient {
	v, err := c.gc.Get(generateKey(vendor, bucket))
	if err != nil {
		return nil
	}
	switch res := v.(type) {
	case *inner_tos.Client:
		return res
	case *s3.Client:
		return res
	}
	return nil
}

func generateKey(vendor, bucket string) string {
	return "object_storage:" + vendor + ":" + bucket
}
